package com.gitee.wsl.io.fetcher

import com.gitee.wsl.io.cache.LoadedManifest
import com.gitee.wsl.io.div
import com.gitee.wsl.io.hex
import com.gitee.wsl.io.read
import kotlinx.io.bytestring.ByteString
import kotlinx.io.files.FileSystem
import kotlinx.io.files.Path
import kotlinx.io.readByteString


/**
 * Fetch from embedded fileSystem that ships with the app.
 */
internal class FsEmbeddedFetcher(
    private val embeddedFileSystem: FileSystem,
    private val embeddedDir: Path,
) : Fetcher<ByteString?> {

    override suspend fun fetch(
        applicationName: String,
        eventListener: EventListener,
        id: String,
        sha256: ByteString,
        nowEpochMs: Long,
        baseUrl: String?,
        url: String,
    ): ByteString? = fetchByteString(embeddedDir / sha256.hex())

    fun loadEmbeddedManifest(applicationName: String): LoadedManifest? {
        val manifestBytes = fetchByteString(
            filePath = embeddedDir / getApplicationManifestFileName(applicationName),
        ) ?: return null
        return LoadedManifest(manifestBytes)
    }

    private fun fetchByteString(filePath: Path) = when {
        embeddedFileSystem.exists(filePath) -> embeddedFileSystem.read(filePath) {
            readByteString()
        }
        else -> null
    }

    private fun getApplicationManifestFileName(path:String)=path
}

